package com.vlobakov.homework4.FileAnalizer;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class ReadDataFromTxt {

	private String filePath;
	private String delimitersForSeparatingWords = "[ .,;:?!\\|\\-~'\\\\\"*/\\^()_+=@#$%&*`{}\\[\\]]+";
	private String[] wordsInLine;
	private Map<String, Integer> wordsMap = new HashMap<String, Integer>();
	ValueComparator bvc = new ValueComparator(wordsMap);
	TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(bvc);

	public void read() throws Exception {

		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		readFileLineByLine(reader);

	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	private void readFileLineByLine(BufferedReader br) throws IOException {
		String line;
		while ((line = br.readLine()) != null) {
			wordsInLine = line.split(delimitersForSeparatingWords);
			for (int i = 0; i < wordsInLine.length; i++) {
				if (wordsMap.containsKey(wordsInLine[i])) {
					wordsMap.put(wordsInLine[i],
							wordsMap.get(wordsInLine[i]) + 1);
				} else {
					wordsMap.put(wordsInLine[i], 1);
				}
			}
		}
		removeUnnecessarySymbols();
	}

	private void removeUnnecessarySymbols() {
		wordsMap.remove("");
	}

	public String buildString() throws Exception {
		StringBuilder sb = new StringBuilder();

		sorted_map.putAll(wordsMap);

		// for (Entry<String, Integer> entry : sorted_map.entrySet()) {
		// sb.append(" " + entry.getKey() + "\t -- \t" + entry.getValue()
		// + "\n");
		// }

		Object[] keys_array = sorted_map.keySet().toArray();
		Object[] values_array = sorted_map.values().toArray();

		int mapSize = sorted_map.size();
		if (mapSize != 0) {
			sb.append("Word frequency :\n");
		}

		int topThreshhold;
		if (mapSize >= 20) {
			topThreshhold = 20;
		} else if (mapSize == 0) {
			System.out.println("You have no words in your file.");
			topThreshhold = 0;
		} else {
			topThreshhold = mapSize;
		}

		for (int i = 0; i < topThreshhold; i++) {
			sb.append(i + 1 + ": " + keys_array[i] + "\t \t -- \t \t"
					+ values_array[i] + "\n");
		}
		return sb.toString();
	}

	static class ValueComparator implements Comparator<String> {

		Map<String, Integer> base;

		public ValueComparator(Map<String, Integer> wordsMap) {
			this.base = wordsMap;
		}

		// Note: this comparator imposes orderings that are inconsistent with
		// equals.
		public int compare(String a, String b) {
			if (base.get(a) >= base.get(b)) {
				return -1;
			} else {
				return 1;
			} // returning 0 would merge keys
		}
	}

}
